<template>
  <div id="Cart">
    <section class="jarallax py-5">
      <img src="@/assets/images/banner-1.jpg" class="jarallax-img">
      <div class="hero-content py-0 py-md-5">
        <div class="container-lg d-flex flex-column d-md-block align-items-center">
          <nav class="breadcrumb">
            <a class="breadcrumb-item nav-link" href="/Organic/home">主页</a>
            <a class="breadcrumb-item nav-link" href="/Organic/login">页面</a>
            <span class="breadcrumb-item active" aria-current="page">购物车</span>
          </nav>
          <h1>购物车</h1>
        </div>
      </div>
    </section>

    <section class="py-5">
      <div class="container-lg">
        <div class="row g-5">
          <div class="col-md-8">

            <div class="table-responsive cart">
              <table class="table">
                <thead>
                <tr>
                  <th scope="col" class="card-title text-uppercase text-muted" >商品</th>
                  <th scope="col" class="card-title text-uppercase text-muted">数量</th>
                  <th scope="col" class="card-title text-uppercase text-muted" style="width: 100px">小计</th>
                  <th scope="col" class="card-title text-uppercase text-muted"></th>
                </tr>
                </thead>
                <tbody>
                  <tr v-for="(cart) in carts" :key="cart.cartId">
                    <td scope="row" class="py-4" >
                      <div class="cart-info d-flex flex-wrap align-items-center mb-4">
                        <div class="col-lg-3">
                          <div class="card-image">
                            <img :src="'http://localhost:90'+cart.product.imgLink" alt="product name" class="img-fluid">
                          </div>
                        </div>
                        <div class="col-lg-9">
                          <div class="card-detail ps-3">
                            <h5 class="card-title">
                              <a href="#" class="text-decoration-none">{{cart.product.name}}</a>
                            </h5>
                          </div>
                        </div>
                      </div>
                    </td>
                    <td class="py-4">
                      <div class="input-group product-qty w-50">
                        <span class="input-group-btn">
                          <button type="button" class="quantity-left-minus btn btn-light btn-number" data-type="minus" @click="updateQuantity(cart, 'minus')">
                            <svg width="16" height="16">
                              <use xlink:href="#minus"></use>
                            </svg>
                          </button>
                        </span>
                        <input type="text" id="quantity" name="quantity" class="form-control input-number text-center" :value="cart.num">
                        <span class="input-group-btn">
                          <button type="button" class="quantity-right-plus btn btn-light btn-number" data-type="plus" @click="updateQuantity(cart, 'plus')" data-field="">
                            <svg width="16" height="16">
                              <use xlink:href="#plus"></use>
                            </svg>
                          </button>
                        </span>
                      </div>
                    </td>
                    <td class="py-4">
                      <div class="total-price">
                        <span class="money text-dark">{{ cart.product.price * cart.num }}元</span>
                      </div>
                    </td>
                    <td class="py-4">
                      <div class="cart-remove">
                        <a href="#" @click="removeCart(cart)">
                          <svg width="24" height="24">
                            <use xlink:href="#trash"></use>
                          </svg>
                        </a>
                      </div>
                    </td>
                  </tr>

                </tbody>
              </table>
            </div>

          </div>
          <div class="col-md-4">
            <div class="cart-totals bg-grey py-5">
              <h4 class="text-dark pb-4">购物车总金额</h4>
              <div class="total-price pb-5">
                <table cellspacing="0" class="table text-uppercase">
                  <tbody>
                    <tr class="subtotal pt-2 pb-2 border-top border-bottom">
                      <th>小计</th>
                      <td data-title="Subtotal">
                        <span class="price-amount amount text-dark ps-5">
                          <bdi>
                            <span class="price-currency-symbol" v-text="subtotal+'元'"></span>
                          </bdi>
                        </span>
                      </td>
                    </tr>
                    <tr class="order-total pt-2 pb-2 border-bottom">
                      <th>总额</th>
                      <td data-title="Total">
                        <span class="price-amount amount text-dark ps-5">
                          <bdi>
                            <span class="price-currency-symbol" v-text="totalPrice+'元'"></span>
                          </bdi>
                        </span>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
              <div class="button-wrap row g-2">
                <div class="col-md-6">
                  <button class="btn btn-dark py-3 px-4 text-uppercase btn-rounded-none w-100" @click="UpdateCarts">更新购物车</button>
                </div>
                <div class="col-md-6">
                  <button class="btn btn-dark py-3 px-4 text-uppercase btn-rounded-none w-100" @click="goToShop">继续购物</button>
                </div>
                <div class="col-md-12">
                  <button class="btn btn-primary py-3 px-4 text-uppercase btn-rounded-none w-100" @click="goToCheckout">前往结帐</button>
                </div>
              </div>
            </div>
          </div>

        </div>
      </div>
    </section>
  </div>
</template>

<script>
export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'Cart',
  components: {},
  props: {},
  data () {
    return {
      user: {},
      carts: []
    }
  },
  // 计算属性 类似于data概念
  computed: {
    subtotal() {
      return this.carts.reduce((sum, cart) => sum + cart.product.price * cart.num, 0);
    },
    totalPrice() {
      return this.carts.reduce((sum, cart) => sum + cart.product.price * cart.num, 0);
    }
  },
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    intUser(){
      this.user=this.$store.state.user;
    },
    intCart(){
      this.$axios.get('http://localhost:8090/cart/getCartByConsumerId?consumerId=' + this.user.consumerId).then(({ data }) => {
        // eslint-disable-next-line no-empty
        if(data !== null && data !== undefined ){
          this.carts = data;
          console.log(this.carts);
          this.$store.commit('initCarts', this.carts)
          console.log(this.$store.state.carts);
        }
      })
    },
    updateQuantity(cart, type) {
      const index = this.carts.indexOf(cart);
      if (type === 'minus') {
        this.$set(this.carts[index], 'num', cart.num - 1 < 1 ? 1 : cart.num - 1);
      } else if (type === 'plus') {
        this.$set(this.carts[index], 'num', cart.num + 1);
      }
      this.$forceUpdate(); // 强制重新渲染，触发计算属性更新
    },
    UpdateCarts(){
      this.$axios.put('http://localhost:8090/cart/updateCart', this.carts).then(({ data }) => {
        if (data) {
          this.$notify({
            title: '更新成功',
            message: '更新成功！',
            type: 'success'
          });
          this.intCart()
        }else{
          this.$notify({
            title: '更新失败',
            message: '更新失败，请稍后重试',
            type: 'warning'
          });
        }
      })
    },
    goToCheckout(){
      this.$router.push({ path: '/Organic/checkout' });
    },
    goToShop(){
      this.$router.push({ path: '/Organic/shop' });
    },
    removeCart(cart){
      this.$axios.delete('http://localhost:8090/cart/deleteCart?cartId=' + cart.cartId).then(({ data }) => {
        if (data) {
          this.$notify({
            title: '删除成功',
            message: '删除成功！',
            type: 'success'
          });
          this.intCart()
        }else{
          this.$notify({
            title: '删除失败',
            message: '删除失败，请稍后重试',
          })
        }
      })
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
    this.intUser();
    this.intCart();
  },
  // 生命周期 - 创建之前
  beforeCreate () {},
  // 生命周期 - 挂载之前
  beforeMount () {},
  // 生命周期 - 更新之前
  beforeUpdate () {},
  // 生命周期 - 更新之后
  updated () {},
  // 生命周期 - 销毁之前
  beforeDestroy () {},
  // 生命周期 - 销毁完成
  destroyed () {},
  // 如果页面有keep-alive缓存功能，这个函数会触发
  activated () {}
}
</script>

<style scoped>

</style>
